package com.share.thread.future;

import java.util.Collections;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.*;

/**
 * @desc:
 * @author:caifan
 * @date:2022/3/31
 */
public class CompletableFutureTravelDemo {

    public static void main(String[] args) {
        CompletableFutureTravelDemo completableFutureTravelDemo = new CompletableFutureTravelDemo();
        System.out.println(completableFutureTravelDemo.getPrices());
    }


    private Set<Integer> getPrices() {
        Set<Integer> prices = Collections.synchronizedSet(new HashSet<Integer>());
        CompletableFuture task1 = CompletableFuture.runAsync(new Task(123, prices));
        CompletableFuture task2 = CompletableFuture.runAsync(new Task(456, prices));
        CompletableFuture task3 = CompletableFuture.runAsync(new Task(789, prices));
        CompletableFuture<Void> all = CompletableFuture.allOf(task1, task2, task3);
        try {
            all.get(1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return prices;
    }

    private class Task implements Runnable {
        private final Integer productId;
        private final Set<Integer> prices;

        public Task(Integer productId, Set<Integer> prices) {
            this.productId = productId;
            this.prices = prices;
        }

        @Override
        public void run() {
            int price = 0;
            try {
                Thread.sleep(new Random().nextInt(3) * 1000);
                price = new Random().nextInt(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            prices.add(price);
        }
    }
}
